package com.evil.application.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.evil.application.pojo.entity.ApplicationOrderData;
import com.evil.common.core.enums.RCodeEnum;
import com.evil.common.core.exception.BusinessException;
import com.evil.common.core.util.StreamUtil;
import com.evil.common.db.mapper.BatchMapper;
import org.apache.ibatis.annotations.Param;

import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * @author liyang
 * @date 2023-01-30 14:36
 */
public interface ApplicationOrderDataMapper extends BaseMapper<ApplicationOrderData>, BatchMapper<ApplicationOrderData, Long> {

    int updateBatch(List<ApplicationOrderData> list);

    int batchInsert(@Param("list") List<ApplicationOrderData> list);

    Optional<ApplicationOrderData> isExistById(Long id);

    default ApplicationOrderData findById(Long id) {
        return this.isExistById(id).orElseThrow(() -> new BusinessException(RCodeEnum.APPLICATION_ORDER_DATA_NOT_EXIST));
    }

    List<ApplicationOrderData> findByIds(@Param("ids") Collection<Long> ids, @Param("filterDeleted") boolean filterDeleted);

    List<ApplicationOrderData> findByOrderId(@Param("orderId") Long orderId);

    List<ApplicationOrderData> findByOrderIds(@Param("orderIds") Collection<Long> orderIds, @Param("filterDeleted") boolean filterDeleted);

    List<ApplicationOrderData> orderControlDataList(@Param("orderId") Long orderId, @Param("controlId") Long controlId);

    Optional<ApplicationOrderData> isExistOrderControlFirstData(@Param("orderId") Long orderId, @Param("controlId") Long controlId);

    default ApplicationOrderData findOrderControlFirstData(Long orderId, Long controlId) {
        return this.isExistOrderControlFirstData(orderId, controlId).orElseThrow(() -> new BusinessException(RCodeEnum.ERROR_RUNTIME));
    }

    List<ApplicationOrderData> orderControlsFirstData(@Param("orderId") Long orderId, @Param("controlIds") Collection<Long> controlIds);

    default Map<Long, ApplicationOrderData> controlFirstDataMap(Long orderId, Collection<Long> controlIds) {
        List<ApplicationOrderData> orderDataList = this.orderControlsFirstData(orderId, controlIds);
        if (orderDataList.size() != controlIds.size()) {
            throw new BusinessException(RCodeEnum.ERROR_RUNTIME);
        }
        return StreamUtil.toOrderlyMapK(orderDataList, ApplicationOrderData::getControlId);
    }
}